package javapop.framework.parser;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javapop.framework.ParseContext;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class TupleParser extends Parser<List<?>> {
	private List<Parser<?>> children;
	private Set<Integer> components;
	private String description;
	private int fatalFrom;
	
	public TupleParser(List<Parser<?>> children, Integer...components) {
		this.children = children;
		this.components = new TreeSet<Integer>();
		for(Integer comp : components) {
			this.components.add(comp);
		}
		description = null;
		fatalFrom = -1;
	}
		
	public TupleParser() {
		children = new ArrayList<Parser<?>>();
		components = new HashSet<Integer>();
		description = null;
		fatalFrom = -1;
	}
	
	public void setFatalFrom(int ref) {
		if(ref<0 || ref>=children.size()) {
				throw new IllegalArgumentException("Cannot set fatal : wrong ref = "+ref);
		}
		fatalFrom = ref;
	}

	public int getArity() {
		return components.size();
	}

	public void addSilent(Parser<?> child) {
		children.add(child);
	}
	
	public void addComponent(Parser<?> component) {
		int index = children.size();
		addSilent(component);
		components.add(index);
	}
	
	@Override
	public String getDescription() {
		if(description==null) {
			StringBuffer buf = new StringBuffer();
			for(Parser<?> child : children) {
				buf.append(child.toString());
				buf.append(" ");
			}
			description = buf.toString();
		}
		return description;
	}
	
	@Override
	public boolean isMemoized() {
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<List<?>> eval(ParseContext ctx, ParseInput input) {
		List<Object> results = new ArrayList<Object>();
		for(int i=0;i<children.size();i++) {
			Parser<?> parser = children.get(i);
			ParseResult<?> result = parser.parse(ctx,input);
			if(result.isError()) {
				if(fatalFrom!=-1 && i>=fatalFrom) {
					result.asError().setFatal(true);
				}
				return (ParseResult) result.asError();
			}
			if(components.contains(i)) {
				/* XXX: allow null parse in components ? (why not ?)
				if(result.isNull()) {
					return (ParseResult) new ParseError(""+(i+1)+"-th components of tuple has null parse",true);
				} */
				results.add(result.getResult());
			}
		}
		return buildResult(results);
	}
	
}
